import { Interceptor, NestInterceptor, ExecutionContext } from '@nestjs/common';
import { configure, getLogger } from 'log4js';
import { config } from '../config/log.config';
import { Observable } from 'rxjs/Observable';
import { Request } from 'express';
import 'rxjs/add/operator/do';

// logger设置与获取
configure(config);
const logger = getLogger('default');
/**
 * 日志拦截器   （不重要，可不看）
 *
 * @export
 * @class LoggingInterceptor
 * @implements {NestInterceptor}
 */
@Interceptor()
export class LoggingInterceptor implements NestInterceptor {
  intercept(
    dataOrRequest: Request,
    context: ExecutionContext,
    stream$: Observable<any>,
  ): Observable<any> {
    const now = Date.now();
    return stream$.do(() => {
      logger.info(
        `received from ${dataOrRequest.ip}  { ${dataOrRequest.path}, ${
          dataOrRequest.method
        } } and costs ${Date.now() - now} ms`,
      );
    });
  }
}
